<?php

/**
 * This is the model class for table "series".
 *
 * The followings are the available columns in table 'series':
 * @property string $id
 * @property string $name
 * @property integer $time_create
 * @property integer $time_update
 * @property string $url
 * @property string $desc
 * @property string $color
 * @property integer $weight
 *
 *
 * @property Topic[] $topics
 */
class Series extends CActiveRecord
{

    public $time_begin;
    public $time_end;
    public $searchKey;

    public $tids;

    private static $_options;


    protected function afterSave()
    {
        $this->updateTopics();
        parent::afterSave(); // TODO: Change the autogenerated stub
    }

    protected function afterFind()
    {
        if (empty($this->tids)) {
            $this->tids = array_map(function ($topic) {
                return $topic->id;
            }, $this->topics);
        }
        parent::afterFind(); // TODO: Change the autogenerated stub
    }


    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'series';
    }


    public static function getOptions($attribute, $options = array())
    {
        if (!isset(self::$_options[$attribute])) {
            $opts = [];
            switch ($attribute) {
                case 'series':
                    $seriesse = Series::model()->findAll();
                    foreach ($seriesse as $series) {
                        $opts[$series->id] = $series->name;
                    }
                    break;
            }
            self::$_options[$attribute] = $opts;
        }
        if (is_array($options) && !empty($options)) {
            foreach (self::$_options[$attribute] as $k => $v) {
                $options[$k] = $v;
            }
        } else {
            $options = self::$_options[$attribute];
        }
        return $options;
    }


    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        return array(
            array('weight,time_create, time_update', 'numerical', 'integerOnly' => true),
            array('name, desc', 'length', 'max' => 11),
            array('url,color', 'length', 'max' => 64),
            array('desc', 'length', 'max' => 128),
            array('id, name, time_create, time_update, url, color,desc', 'safe', 'on' => 'search'),
            array('name', 'required'),
            array('color', 'required'),
            array('name', 'unique', 'on' => 'insert'),
            array('url', 'url'),
            array('time_begin, time_end,tids,searchKey', 'safe'),
            array(
                'time_update',
                'default',
                'value' => time(),
                'setOnEmpty' => false,
                'on' => 'update'
            ),
            array(
                'time_create, time_update',
                'default',
                'value' => time(),
                'setOnEmpty' => false,
                'on' => 'insert'
            ),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        return array(
            'topics' => array(self::MANY_MANY, 'Topic', 'series_topic(sid, tid)'),
            'series_topic' => array(self::HAS_MANY, 'SeriesTopic', ['sid' => 'id']),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'name' => '分类名称',
            'time_create' => 'Time Create',
            'time_update' => 'Time Update',
            'url' => '分类图标url',
            'color' => '分类颜色',
            'desc' => 'Desc',
            'weight' => '权重',
            'tids' => '关联主题',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function searchByKey()
    {

        $criteria = new CDbCriteria;
        if (!isset($_GET['Topic_sort'])) {
            $criteria->order = 't.id DESC';
        }

        if (!empty($ts_begin = strtotime($this->time_begin))) {
            $criteria->addCondition('`time_create` >= ' . $ts_begin);
        }
        if (!empty($ts_end = strtotime($this->time_end))) {
            $criteria->addCondition('`time_create` <= ' . $ts_end);
        }

        if ($this->searchKey !== '') {
            $criteria->compare('name', $this->searchKey, true);
            $criteria->compare('url', $this->searchKey, true);
            $criteria->compare('`desc`', $this->searchKey, true);
        }

        $criteria->order = 'weight desc';
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => 5,
            ),
        ));
    }


    public function updateTopics()
    {
        $topics = array_map(function ($topic) {
            return $topic->id;
        }, $this->topics);
        foreach ($this->tids as $tid) {
            if (!in_array($tid, $topics)) {
                $seriesTopic = SeriesTopic::build($this->id, $tid);
                if (!$seriesTopic->save()) {
                    return false;
                }
            }
        }
        $criteria = new CDbCriteria();
        $criteria->addColumnCondition(['sid' => $this->id,]);
        $criteria->addNotInCondition('tid', $this->tids);
        SeriesTopic::model()->deleteAll($criteria);
        return true;
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Series the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }
}
